var mongoose = require("mongoose");
var News = require('../modules/news.module');
var Comment = require('../modules/comment.module');

var async = require('async');

exports.create = function(req, res, next) {
    const news = new News(req.body);

    news.save(function(err, data) {
        if (err) {
            console.log(err);
        } else {
            res.json(data);
        }
    });
}

exports.update = function(req, res, next) {
    const news = new News(req.body);
    const id = req.params.id;
    // console.log()
    News.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
        res.json(data);
    });
};
exports.remove = function(req, res, next) {
    const id = req.params.id;

    News.findByIdAndRemove(id, function(err, data) {
        res.json({ message: "delete ok" });
    });
};

exports.list = function(req, res, next) {
    var page = (req.body.page) ? req.body.page : 1;
    var limit = (req.body.limit) ? req.body.limit : 3;
    var queryCondition = {};

    if (req.body.cateId && req.body.cateId.trim().length) {
        cateId = req.body.cateId;
        queryCondition = {
            cateId: cateId
        }
    }
    if (req.body._id) {
        queryCondition = {
            _id: req.body._id
        }
    }



    if (req.body.title && req.body.title.trim().length) {
        title = req.body.title;
        //对象合并Object.assign
        queryCondition = Object.assign(queryCondition, {
            "title": new RegExp(title, "i")
        })
    }
    News.paginate(queryCondition, { page: page, limit: limit }, function(
        err,
        results
    ) {
        // res.json(results);
        //注意代码执行的异步同步1.安装异步模块 cnpm i async -S   
        //2.打开async官网 引入map
        // for(let i=0;i<results.docs.length;i++){
        // console.log(results.docs[i]._id);
        // Comment.count({cateId:results.docs[i]._id})
        // .then(data=>{
        //     console.log(data);
        //     results.docs[i].commentCount=data;
        // })

        // }
        //map循环遍历新闻字段
        async.map(results.docs, function(news, callback) {

            Comment.count({ text: news._id }).then(data => {
                console.log(data)
                news.commentCount = data;
                callback(null, news)
            })
        }, function(err) {
            res.json(results)
        })
    })

};